package com.elong.android.specialhouse.payment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.payment.bean.GetBefundTokenReq;
import com.elong.android.specialhouse.utils.Utils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;
import com.elong.payment.AbsPaymentCounterActivity;
import com.elong.payment.base.PaymentConstants;
import com.elong.payment.dialogutil.IHttpErrorConfirmListener;
import com.elong.payment.utils.MathUtils;
import com.elong.payment.utils.PaymentUtil;

public class ApartmentPaymentCounterImpl extends AbsPaymentCounterActivity {


    /**
     * 标识顶部紧急文案是否展开
     */
    private boolean isExpandedFlag = false;

    private TextView headView;
    private ImageView headSwitch;
    // 是否是担保酒店
    private boolean isVouch = false;
    // 是否即时确认
    private boolean isInstant = false;
    // 订单担保类型,1:先授权后确认 2: 先确认后授权
    private int authorizeType = 1;
    // 判断支付的订单是否是来自成单
    private boolean isFromGenerateOrder;

    @Override
    public void initLocalData(Bundle savedInstanceState) {
        super.initLocalData(savedInstanceState);
        Intent intent = getIntent();
//        isVouch = intent.getBooleanExtra(PaymentConstants.IsVouch, false);
//        isInstant = intent.getBooleanExtra(PaymentConstants.IsInstant, false);
//        authorizeType = intent.getIntExtra(PaymentConstants.AuthorizeType, 0);
//        isFromGenerateOrder = intent.getBooleanExtra(PaymentConstants.isFromGenerateOrder, false);
    }

    @Override
    protected void setPriceInfo() {
        setPriceData("￥ " + MathUtils.doubleFormat(totalPrice), getTotalPriceTag());
    }

    @Override
    public void requestServerData() {
        super.requestServerData();
        // 来自个人中心的订单详情不请求订单确认结果,只有来自成单才请求
//        if (isFromGenerateOrder) {
//            getOrderProcess(false);
//        }
    }


    @Override
    protected void setBizType() {
        //todo
//        bizType = PaymentConstants.BIZTYPE_APARTMENT_PREPAY;
        bizType = 1017 ;
    }

    protected String getTotalPriceTag() {
        return getString(R.string.pay_total_price);
    }

//    /**
//     * 请求文案
//     */
//    private void getOrderProcess(boolean ispaySuccess) {
//        int payStatus = ispaySuccess ? 1 : 0;
//        if (Utils.isEmptyString(orderId)) {
//            return;
//        }
//        GetApartmentOrderConfirmInfoReq request = new GetApartmentOrderConfirmInfoReq();
//        request.OrderId = Integer.valueOf(orderId);
//        request.PayStatus = payStatus;
//        request.IsVouch = isVouch;
//        request.IsInstant = isInstant;
//        request.AuthorizeType = authorizeType;
//        requestHttp(request, PaymentExtraApi.getPayToken, StringResponse.class);
//    }


    /**
     * 可能在下单成功返回信息中没有带回来，需要再取一下，因为调用的接口以及使用的URl不一定一致，所以在各自的业务内实现这个方法。
     */
    @Override
    public void tryRequestBefundToken() {
        if (!Utils.isEmptyString(notifyUrl)) {
            return;
        }
        GetBefundTokenReq req = new GetBefundTokenReq();
        // todo
        req.gOrderId = orderId;
        requestHttp(req, PaymentExtraApi.getPayToken, StringResponse.class, true);
        Log.d("Payment", req.getUrl());
    }

    @Override
    public void processTask(ElongRequest request, IResponse<?> t) {
        super.processTask(request, t);
        if (!request.getRequestOption().getHusky().getClass().equals(PaymentExtraApi.class)) {
            return;
        }
        String result = ((StringResponse) t).getContent();
        Log.d("payToken response-->", t == null ? "" : result);
        if (IsRespError(result)) {
            tryGetTokenAgain(result);
            return;
        }
        switch ((PaymentExtraApi) request.getRequestOption().getHusky()) {
            case getPayToken:
                try {
                    resolveGetTokenData(JSON.parseObject(result));
                } catch (JSONException e) {
                    PaymentUtil.showInfo(this, getString(R.string.pay_back_error));
                }

                break;
//                case hotel_hotelOrderConfirmInfo:
//                    try {
//                        OrderConfirmInfo orderConfirmInfo = JSON.parseObject(t.toString(), OrderConfirmInfo.class);
//                        if (SPUtil.getInstance().getIsInstant(this) == false && SPUtil.getInstance().getAuthorizeType(this) == 2) {
//                            // 非即时确认和先成单后支付的订单提示文案
//                            refreshOrderConfirmInfoView(orderConfirmInfo);
//                        } else {
//                            refreshOrderConfirmInfoRiskDescListView(orderConfirmInfo);
//                        }
//                    } catch (JSONException e) {
//                        PaymentUtil.showInfo(this, getString(R.string.hotel_order_payback_error));
//                    }
//                    break;
        }
    }


    //获取token信息请求超过三次未能获取到数据，则停止请求
    private int requestTokenCount = 0;
    private final int requestMaxLimited = 2;

    private void tryGetTokenAgain(String respStr) {
        JSONObject response = JSON.parseObject(respStr);
        PaymentUtil.showInfo(this, response.getString(PaymentConstants.ErrorMessage), new IHttpErrorConfirmListener() {
            @Override
            public void onHttpErrorConfirm(ElongRequest request) {
                if (requestTokenCount > requestMaxLimited) {
                    return;
                }
                requestTokenCount++;
                tryRequestBefundToken();
            }

            @Override
            public void onHttpContinue(ElongRequest request) {

            }
        });
    }

    private boolean IsRespError(String respStr) {
        JSONObject response = JSON.parseObject(respStr);
        return response.getBooleanValue(PaymentConstants.IsError);
    }

    @Override
    public void onValueSelected(int id, Object... values) {

    }

//    private void refreshOrderConfirmInfoRiskDescListView(OrderConfirmInfo info) {
//        if (Utils.isEmptyString(info)) {
//            return;
//        }
//        // ---风险描述
//        RiskDescList riskDescList = info.getRiskDescList();
//        if (!Utils.isEmptyString(riskDescList) && !Utils.isEmptyString(riskDescList.getInfos()) && riskDescList.getInfos().size() > 0) {
//            StringBuilder sb = new StringBuilder();
//            for (int i = 0; i < riskDescList.getInfos().size(); i++) {
//                sb.append((i + 1) + "." + riskDescList.getInfos().get(i));
//                if (i != riskDescList.getInfos().size() - 1) {
//                    sb.append('\n');
//                }
//            }
//            // 应Pm要求去掉字符串中“1.”等字符串，api没有给我新的接口，只能这样暂时兼容一下
//            String riskDesStr = sb.toString().replace("1.", "").replace("2.", "").replace("3.", "").replace("4.", "").replace("5.", "");
//            if (foot2 != null) {
//                foot2.setTextColor(getResources().getColor(R.color.common_red));
//                foot2.setVisibility(View.VISIBLE);
//                foot2.setText(riskDesStr);
//            }
//        }
//    }

//    private void refreshOrderConfirmInfoView(OrderConfirmInfo info) {
//        if (Utils.isEmptyString(info)) {
//            return;
//        }
//        /** 房描述和处理时间 */
//        StringBuilder roomDescAndTime = null;
//        // ---是否有房描述
//        RoomDescList roomDescList = info.getRoomDescList();
//        if (!Utils.isEmptyString(roomDescList) && !Utils.isEmptyString(roomDescList.getInfos()) && roomDescList.getInfos().size() > 0) {
//            roomDescAndTime = new StringBuilder();
//            for (int i = 0; i < roomDescList.getInfos().size(); i++) {
//                roomDescAndTime.append(roomDescList.getInfos().get(i));
//            }
//        }
//        // ---处理时间描述
//        String timeDes = null;
//        int timePositon = -1;
//        ProcessTimeDescList processTimeDescList = info.getProcessTimeDescList();
//        if (!Utils.isEmptyString(processTimeDescList) && !Utils.isEmptyString(processTimeDescList.getInfos())
//                && processTimeDescList.getInfos().size() > 0) {
//            timeDes = processTimeDescList.getInfos().get(0);
//            timePositon = processTimeDescList.getPosition();
//            if (timePositon == 0) {// 处理时间在是否有房之后
//                // roomProcessTime1.setText("(" + timeDes + ")");
//                roomDescAndTime.append("(" + timeDes + ")，");
//            }
//        }

    // ---支付顺序 应pm需求暂时去掉支付顺序
    // AuthorizeTypeList authorizeTypeList = info.getAuthorizeTypeList();
    // if (!Utils.isEmptyString(authorizeTypeList) && !Utils.isEmptyString(authorizeTypeList.getInfos())
    // && authorizeTypeList.getInfos().size() > 0) {
    // int len = authorizeTypeList.getInfos().size();
    // for (int i = 0; i < len; i++) {
    // roomDescAndTime.append(authorizeTypeList.getInfos().get(i)+"。");
    // }
    //
    // }
    // ---风险描述
//        RiskDescList riskDescList = info.getRiskDescList();
//        if (!Utils.isEmptyString(riskDescList) && !Utils.isEmptyString(riskDescList.getInfos()) && riskDescList.getInfos().size() > 0) {
//            StringBuilder sb = new StringBuilder();
//            for (int i = 0; i < riskDescList.getInfos().size(); i++) {
//                roomDescAndTime.append(riskDescList.getInfos().get(i) + "。");
//            }
//        }
//        if (roomDescAndTime == null || Utils.isEmptyString(roomDescAndTime.toString())) {
//            return;
//        }
//        if (emergencyView != null) {
//            emergencyView.setTextColor(getResources().getColor(R.color.common_red));
//            emergencyView.setVisibility(View.VISIBLE);
//            emergencyView.setLines(2);
//            emergencyView.setEllipsize(TextUtils.TruncateAt.END);
//            emergencyView.setText(roomDescAndTime.toString());
//            if (emergencySwitch != null) {
//                emergencySwitch.setOnClickListener(this);
//                emergencySwitch.setVisibility(View.VISIBLE);
//            }
//            if (emergencyContaniner != null && (emergencyView.getVisibility() == View.VISIBLE) && emergencySwitch != null) {
//                emergencyContaniner.setVisibility(View.VISIBLE);
//            }
//        }
//
//        // 默认文案是不展开的
//        isExpandedFlag = false;
//    }

//    @Override
//    public void onClick(View v) {
//        int id = v.getId();
//        if (id == R.id.payment_counter_emergency_info_switch) {
//            if (emergencyView != null && emergencySwitch != null) {
//                if (isExpandedFlag) {
//                    isExpandedFlag = false;
//                    emergencySwitch.setImageResource(R.drawable.payment_counter_emergency_head_switch_pressed);
//                    emergencyView.setSingleLine(false);
//                    emergencyView.setEllipsize(null);
//                } else {
//                    isExpandedFlag = true;
//                    emergencySwitch.setImageResource(R.drawable.payment_counter_emergency_head_switch_normal);
//                    emergencyView.setLines(2);
//                    emergencyView.setEllipsize(TextUtils.TruncateAt.END);
//                }
//            }
//        }
//        super.onClick(v);
//    }

//    @Override
//    protected Intent getCAPasswordResetActivityIntent(Context context) {
//        try {
//            Intent intent = Mantis.getPluginIntent(context, ActivityConfig.MyElongCashSetPwdActivity.getPackageName(),
//                    ActivityConfig.MyElongCashSetPwdActivity.getAction());
//            return intent;
//        } catch (Exception e) {
//            LogWriter.logException(TAG, LogWriter.LOG_LEVEL_NORMAL, e);
//            return null;
//        }
//    }

}
